package com.neuedu.yyzx.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.neuedu.yyzx.common.Ret;
import com.neuedu.yyzx.po.User;
import com.neuedu.yyzx.service.UserService;
import com.neuedu.yyzx.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 金山
 * 项目：yyzx
 * site: https://blog.fulfill.com.cn
 * 描述
 * @data 2025/3/288:50
 */
@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;


    @RequestMapping("/login")
    public Ret<String> login(User user) throws Exception {

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, user.getUsername());


        User queryUser = userService.getOne(queryWrapper);
        if (queryUser == null) {
            throw new Exception("用户名和密码不正确");
        }


        String encodePassword = queryUser.getPassword();

        boolean matches = passwordEncoder.matches(user.getPassword(), encodePassword);
        if (!matches) {
            throw new Exception("用户名和密码不正确");
        }


        // 密码正确

        // 生成Token

        String token = JWTUtils.create(queryUser);


        return Ret.ok(token);

    }


}
